package com.kob.botrunningsysytem.service.impl.utils;

import com.kob.botrunningsysytem.utils.BotInterface;
import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

/**
 * 执行botcode代码 并返回给backend的reciveBotmovecontroller结果
 */
@Component
public class Consumer extends Thread {
    private Bot bot;
    private static RestTemplate restTemplate;
    private final static String receiveBotMoveUrl = "http://127.0.0.1:3000/pk/receive/bot/move/";
    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void startTimeout(long timeout,Bot bot){
        this.bot=bot;
        this.start();
        try {
            this.join(timeout);//最多等待timeout秒
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            this.interrupt();// 终止当前线程
        }
    }

    private String addUid(String code,String uid){// 在code中的Bot类名后添加uid
        int k = code.indexOf(" implements com.kob.botrunningsystem.utils.BotInterface");
        return code.substring(0, k) + uid + code.substring(k);
    }
    @Override
    public void run(){
        UUID uuid= UUID.randomUUID();//防止类名相同，只会编译一次
        String uid=uuid.toString().substring(0,8);
        BotInterface botInterface= Reflect.compile(
                "com.kob.botrunningsysytem.utils.BotInterfaceImpl"+uid,//类字
                addUid(bot.getBotCode(),uid)//类的内容
        ).create().get();
        //user_id direction
        System.out.println("move_direction"+bot.getUserId()+" "+botInterface.nextMove(bot.getInput()));
        MultiValueMap<String,String> data=new LinkedMultiValueMap<>();
        data.add("user_id",bot.getUserId().toString());
        data.add("direction",botInterface.nextMove(bot.getInput()).toString());//解析用户输入的代码，返回走完这一步的结果

        restTemplate.postForObject(receiveBotMoveUrl,data, String.class);
    }

}
